package org.sabeot.enlistme.web.controller;

import javax.faces.application.FacesMessage;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import org.apache.log4j.Logger;
import org.primefaces.context.RequestContext;
import org.sabeot.enlistme.service.UserService;
import org.sabeot.enlistme.utils.exceptions.DatabaseException;
import org.sabeot.enlistme.web.bean.UserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller("editUserController")
@RequestScoped
public class EditUserController {

	Logger logger = Logger.getLogger(EditUserController.class);

	@Autowired
	UserService userService;

	@Autowired
	UserBean userBean;

	private String message;

	public void createNewUser() {

		boolean status = false;

		try{
		status = userService.createNewUser(userBean.getLogin(),
				userBean.getEmail(), userBean.isActive());
		logger.info("User created! " + userBean.getLogin());
		this.message = "User created! " + userBean.getLogin();
		
		}catch(DatabaseException e){
			logger.error("User unable to create!!! " + userBean.getLogin());
			this.message = "User unable to create!!! " + userBean.getLogin() + " email or login already exists";
        }catch(Exception e){
        	logger.error("User unable to create!!! " + userBean.getLogin());
			this.message = "Holey Moley! Something went totally wrong!" + userBean.getLogin();
        }
		
		publishMessage();
		
		reset();
	
	}

	public void publishMessage() {
		FacesContext.getCurrentInstance().addMessage(null,
				new FacesMessage(message));
	}

	
	 public void reset() {
		 this.userBean = new UserBean();
		 RequestContext.getCurrentInstance().reset("new_user_form:new_user_panel");
	 }
	/*
	 * Getters and Setters
	 */

	public UserBean getUserBean() {
		return userBean;
	}

	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}

	public UserService getUserService() {
		return userService;
	}

}
